<template>
  <div class="vue3-cron-plus-container">
    <el-tabs type="border-card">
      <!-- 秒 -->
      <el-tab-pane>
        <template #label>
          <span><el-icon>
              <Calendar />
            </el-icon> 秒</span>
        </template>
        <div class="tabBody myScroller">
          <el-row>
            <el-radio v-model="state.second.cronEvery" label="every">每秒</el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.second.cronEvery" label="cycle">
              周期从
              <el-input-number v-model="state.second.cycleFrom" :min="0" :max="59" />
              到
              <el-input-number v-model="state.second.cycleTo" :min="0" :max="59" />
              秒
            </el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.second.cronEvery" label="interval">
              周期从
              <el-input-number v-model="state.second.intervalFrom" :min="0" :max="59" />
              秒开始，每
              <el-input-number v-model="state.second.intervalStep" :min="1" :max="59" />
              秒执行一次
            </el-radio>
          </el-row>
          <el-row>
            <el-radio class="long" v-model="state.second.cronEvery" label="specific">
              指定
              <el-select multiple v-model="state.second.specificSpecific">
                <el-option v-for="sec in 60" :key="sec - 1" :value="padZero(sec - 1)">
                  {{ padZero(sec - 1) }}
                </el-option>
              </el-select>
            </el-radio>
          </el-row>
        </div>
      </el-tab-pane>

      <!-- 分钟 -->
      <el-tab-pane>
        <template #label>
          <span><el-icon>
              <Calendar />
            </el-icon> 分钟</span>
        </template>
        <div class="tabBody myScroller">
          <el-row>
            <el-radio v-model="state.minute.cronEvery" label="every">分钟</el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.minute.cronEvery" label="cycle">
              周期从
              <el-input-number v-model="state.minute.cycleFrom" :min="0" :max="59" />
              到
              <el-input-number v-model="state.minute.cycleTo" :min="0" :max="59" />
              分钟
            </el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.minute.cronEvery" label="interval">
              周期从
              <el-input-number v-model="state.minute.intervalFrom" :min="0" :max="59" />
              分钟开始，每
              <el-input-number v-model="state.minute.intervalStep" :min="1" :max="59" />
              分钟执行一次
            </el-radio>
          </el-row>
          <el-row>
            <el-radio class="long" v-model="state.minute.cronEvery" label="specific">
              指定
              <el-select multiple v-model="state.minute.specificSpecific">
                <el-option v-for="min in 60" :key="min - 1" :value="padZero(min - 1)">
                  {{ padZero(min - 1) }}
                </el-option>
              </el-select>
            </el-radio>
          </el-row>
        </div>
      </el-tab-pane>

      <!-- 小时 -->
      <el-tab-pane>
        <template #label>
          <span><el-icon>
              <Calendar />
            </el-icon> 小时</span>
        </template>
        <div class="tabBody myScroller">
          <el-row>
            <el-radio v-model="state.hour.cronEvery" label="every">小时</el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.hour.cronEvery" label="cycle">
              周期从
              <el-input-number v-model="state.hour.cycleFrom" :min="0" :max="23" />
              到
              <el-input-number v-model="state.hour.cycleTo" :min="0" :max="23" />
              小时
            </el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.hour.cronEvery" label="interval">
              周期从
              <el-input-number v-model="state.hour.intervalFrom" :min="0" :max="23" />
              小时开始，每
              <el-input-number v-model="state.hour.intervalStep" :min="1" :max="23" />
              小时执行一次
            </el-radio>
          </el-row>
          <el-row>
            <el-radio class="long" v-model="state.hour.cronEvery" label="specific">
              指定
              <el-select multiple v-model="state.hour.specificSpecific">
                <el-option v-for="hour in 24" :key="hour - 1" :value="padZero(hour - 1)">
                  {{ padZero(hour - 1) }}
                </el-option>
              </el-select>
            </el-radio>
          </el-row>
        </div>
      </el-tab-pane>

      <!-- 日 -->
      <el-tab-pane>
        <template #label>
          <span><el-icon>
              <Calendar />
            </el-icon> 日</span>
        </template>
        <div class="tabBody myScroller">
          <el-row>
            <el-radio v-model="state.day.cronEvery" label="every">日</el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.day.cronEvery" label="unspecified">不指定</el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.day.cronEvery" label="cycle">
              周期从
              <el-input-number v-model="state.day.cycleFrom" :min="1" :max="31" />
              到
              <el-input-number v-model="state.day.cycleTo" :min="1" :max="31" />
              日
            </el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.day.cronEvery" label="interval">
              周期从
              <el-input-number v-model="state.day.intervalFrom" :min="1" :max="31" />
              日开始，每
              <el-input-number v-model="state.day.intervalStep" :min="1" :max="31" />
              日执行一次
            </el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.day.cronEvery" label="workday">
              每月
              <el-input-number v-model="state.day.workday" :min="1" :max="31" />
              号最近的那个工作日
            </el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.day.cronEvery" label="last">本月最后一天</el-radio>
          </el-row>
          <el-row>
            <el-radio class="long" v-model="state.day.cronEvery" label="specific">
              指定
              <el-select multiple v-model="state.day.specificSpecific">
                <el-option v-for="day in 31" :key="day" :value="padZero(day)">
                  {{ padZero(day) }}
                </el-option>
              </el-select>
            </el-radio>
          </el-row>
        </div>
      </el-tab-pane>

      <!-- 月 -->
      <el-tab-pane>
        <template #label>
          <span><el-icon>
              <Calendar />
            </el-icon> 月</span>
        </template>
        <div class="tabBody myScroller">
          <el-row>
            <el-radio v-model="state.month.cronEvery" label="every">月</el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.month.cronEvery" label="unspecified">不指定</el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.month.cronEvery" label="cycle">
              周期从
              <el-input-number v-model="state.month.cycleFrom" :min="1" :max="12" />
              到
              <el-input-number v-model="state.month.cycleTo" :min="1" :max="12" />
              月
            </el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.month.cronEvery" label="interval">
              周期从
              <el-input-number v-model="state.month.intervalFrom" :min="1" :max="12" />
              月开始，每
              <el-input-number v-model="state.month.intervalStep" :min="1" :max="12" />
              月执行一次
            </el-radio>
          </el-row>
          <el-row>
            <el-radio class="long" v-model="state.month.cronEvery" label="specific">
              指定
              <el-select multiple v-model="state.month.specificSpecific">
                <el-option v-for="month in 12" :key="month" :value="padZero(month)">
                  {{ padZero(month) }}
                </el-option>
              </el-select>
            </el-radio>
          </el-row>
        </div>
      </el-tab-pane>

      <!-- 周 -->
      <el-tab-pane>
        <template #label>
          <span><el-icon>
              <Calendar />
            </el-icon> 周</span>
        </template>
        <div class="tabBody myScroller">
          <el-row>
            <el-radio v-model="state.week.cronEvery" label="unspecified">不指定</el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.week.cronEvery" label="weekly">周</el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.week.cronEvery" label="cycle">
              周期从星期
              <el-input-number v-model="state.week.cycleFrom" :min="1" :max="7" />
              到星期
              <el-input-number v-model="state.week.cycleTo" :min="1" :max="7" />
            </el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.week.cronEvery" label="nth">
              第
              <el-input-number v-model="state.week.nthWeek" :min="1" :max="5" />
              周的星期
              <el-input-number v-model="state.week.nthDay" :min="1" :max="7" />
            </el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.week.cronEvery" label="last">
              本月最后一个星期
              <el-input-number v-model="state.week.lastDay" :min="1" :max="7" />
            </el-radio>
          </el-row>
          <el-row>
            <el-radio class="long" v-model="state.week.cronEvery" label="specific">
              指定
              <el-select multiple v-model="state.week.specificSpecific">
                <el-option v-for="day in 7" :key="day" :value="day.toString()">
                  星期{{ ['日', '一', '二', '三', '四', '五', '六'][day - 1] }}
                </el-option>
              </el-select>
            </el-radio>
          </el-row>
        </div>
      </el-tab-pane>

      <!-- 年 -->
      <el-tab-pane>
        <template #label>
          <span><el-icon>
              <Calendar />
            </el-icon> 年</span>
        </template>
        <div class="tabBody myScroller">
          <el-row>
            <el-radio v-model="state.year.cronEvery" label="unspecified">不指定</el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.year.cronEvery" label="every">每年</el-radio>
          </el-row>
          <el-row>
            <el-radio v-model="state.year.cronEvery" label="cycle">
              周期从
              <el-input-number v-model="state.year.cycleFrom" :min="1970" :max="2099" />
              到
              <el-input-number v-model="state.year.cycleTo" :min="1970" :max="2099" />
              年
            </el-radio>
          </el-row>
        </div>
      </el-tab-pane>
    </el-tabs>

  </div>
</template>
  
<script lang="ts" setup>
import { reactive, computed, watch } from "vue";
import { Calendar } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

// 常量定义
const CRON_FIELDS = [
  { name: 'second', label: '秒', min: 0, max: 59 },
  { name: 'minute', label: '分钟', min: 0, max: 59 },
  { name: 'hour', label: '小时', min: 0, max: 23 },
  { name: 'day', label: '日', min: 1, max: 31 },
  { name: 'month', label: '月', min: 1, max: 12 },
  { name: 'week', label: '周', min: 1, max: 7 },
  { name: 'year', label: '年', min: 1970, max: 2099 }
] as const;

// 类型定义
interface BaseFieldConfig {
  cronEvery: string;
  cycleFrom: number;
  cycleTo: number;
  intervalFrom?: number;
  intervalStep?: number;
  specificSpecific: string[];
}

interface DayFieldConfig extends BaseFieldConfig {
  workday?: number;
}

interface WeekFieldConfig extends BaseFieldConfig {
  nthWeek: number;
  nthDay: number;
  lastDay: number;
}

interface YearFieldConfig {
  cronEvery: string;
  cycleFrom: number;
  cycleTo: number;
}

interface CronState {
  second: BaseFieldConfig;
  minute: BaseFieldConfig;
  hour: BaseFieldConfig;
  day: DayFieldConfig;
  month: BaseFieldConfig;
  week: WeekFieldConfig;
  year: YearFieldConfig;
  generatedCron: string;
  errorMessage: string;
}

// 默认配置工厂函数
const createDefaultFieldConfig = (): BaseFieldConfig => ({
  cronEvery: 'every',
  cycleFrom: 1,
  cycleTo: 2,
  intervalFrom: 0,
  intervalStep: 1,
  specificSpecific: []
});

const createDefaultDayConfig = (): DayFieldConfig => ({
  ...createDefaultFieldConfig(),
  workday: 1
});

const createDefaultWeekConfig = (): WeekFieldConfig => ({
  cronEvery: 'unspecified',
  cycleFrom: 1,
  cycleTo: 2,
  intervalFrom: 0,
  intervalStep: 1,
  specificSpecific: [],
  nthWeek: 1,
  nthDay: 1,
  lastDay: 1
});

const createDefaultYearConfig = (): YearFieldConfig => ({
  cronEvery: 'unspecified',
  cycleFrom: 2018,
  cycleTo: 2019
});

const state = reactive<CronState>({
  second: createDefaultFieldConfig(),
  minute: createDefaultFieldConfig(),
  hour: createDefaultFieldConfig(),
  day: createDefaultDayConfig(),
  month: createDefaultFieldConfig(),
  week: createDefaultWeekConfig(),
  year: createDefaultYearConfig(),
  generatedCron: '* * * * * ? *',
  errorMessage: ''
});
// 工具函数
const formatNumber = (num: number | string): string => {
  const parsed = typeof num === 'string' ? parseInt(num, 10) : num;
  return isNaN(parsed) ? num.toString() : parsed.toString();
};

const padZero = (num: number): string => {
  return num.toString().padStart(2, '0');
};

// 暴露的方法
const getValue = (): string => {
  return CRON_FIELDS.map(field => expressionData.value[field.name]).join(' ');
};

const setValue = (val: string): void => {
  state.generatedCron = val;
  debugParse(val);
  parseCron();
};

// 添加调试函数来帮助诊断问题
const debugParse = (cronExpression: string): void => {
  console.log('=== 开始解析调试 ===');
  console.log('原始表达式:', cronExpression);

  const parts = cronExpression.split(/\s+/);
  console.log('分割后的部分:', parts);

  const parsedParts = parseCronParts(parts);
  console.log('解析后的部分对象:', parsedParts);

  // 模拟解析过程
  console.log('=== 字段解析结果 ===');

  // 秒字段
  const secondPart = parsedParts.secondPart;
  console.log('秒字段:', secondPart);
  if (secondPart.includes('/')) {
    const [start, step] = secondPart.split('/');
    console.log('秒 - 间隔表达式: start=', start, 'step=', step);
  }

  // 分钟字段
  const minutePart = parsedParts.minutePart;
  console.log('分钟字段:', minutePart);
  if (minutePart.includes('/')) {
    const [start, step] = minutePart.split('/');
    console.log('分钟 - 间隔表达式: start=', start, 'step=', step);
  }

  // 小时字段
  const hourPart = parsedParts.hourPart;
  console.log('小时字段:', hourPart);
  if (hourPart.includes('/')) {
    const [start, step] = hourPart.split('/');
    console.log('小时 - 间隔表达式: start=', start, 'step=', step);
  }

  console.log('=== 结束解析调试 ===');
};

// 优化字段变化检测逻辑
const getFieldChangeStatus = () => {
  const fieldStates = {
    second: state.second.cronEvery,
    minute: state.minute.cronEvery,
    hour: state.hour.cronEvery,
    day: state.day.cronEvery,
    month: state.month.cronEvery,
    week: state.week.cronEvery,
    year: state.year.cronEvery
  };

  const isDefault = (field: string) => {
    const value = fieldStates[field as keyof typeof fieldStates];
    return value === 'every' || value === 'unspecified';
  };

  // 检查哪些字段被修改了
  const modifiedFields = {
    second: !isDefault('second'),
    minute: !isDefault('minute'),
    hour: !isDefault('hour'),
    day: !isDefault('day'),
    month: !isDefault('month'),
    week: !isDefault('week'),
    year: !isDefault('year')
  };

  // 检查特定字段组合的修改情况
  const isOnlyMinuteChanged = modifiedFields.minute &&
    !modifiedFields.second && !modifiedFields.hour && !modifiedFields.day &&
    !modifiedFields.month && !modifiedFields.week && !modifiedFields.year;

  const isOnlyHourChanged = modifiedFields.hour &&
    !modifiedFields.second && !modifiedFields.minute && !modifiedFields.day &&
    !modifiedFields.month && !modifiedFields.week && !modifiedFields.year;

  const isMinuteAndHourChanged = modifiedFields.minute && modifiedFields.hour &&
    !modifiedFields.second && !modifiedFields.day &&
    !modifiedFields.month && !modifiedFields.week && !modifiedFields.year;

  const isMinuteHourDayChanged = modifiedFields.minute && modifiedFields.hour && modifiedFields.day &&
    !modifiedFields.second && !modifiedFields.month && !modifiedFields.week && !modifiedFields.year;

  const isMinuteHourDayMonthChanged = modifiedFields.minute && modifiedFields.hour && modifiedFields.day && modifiedFields.month &&
    !modifiedFields.second && !modifiedFields.week && !modifiedFields.year;

  const isOnlyDayChanged = modifiedFields.day &&
    !modifiedFields.second && !modifiedFields.minute && !modifiedFields.hour &&
    !modifiedFields.month && !modifiedFields.week && !modifiedFields.year;

  const isOnlyMonthChanged = modifiedFields.month &&
    !modifiedFields.second && !modifiedFields.minute && !modifiedFields.hour &&
    !modifiedFields.day && !modifiedFields.week && !modifiedFields.year;

  const isOnlyWeekChanged = modifiedFields.week &&
    !modifiedFields.second && !modifiedFields.minute && !modifiedFields.hour &&
    !modifiedFields.day && !modifiedFields.month && !modifiedFields.year;

  const isOnlyYearChanged = modifiedFields.year &&
    !modifiedFields.second && !modifiedFields.minute && !modifiedFields.hour &&
    !modifiedFields.day && !modifiedFields.month && !modifiedFields.week;

  return {
    modifiedFields,
    isOnlyMinuteChanged,
    isOnlyHourChanged,
    isMinuteAndHourChanged,
    isMinuteHourDayChanged,
    isMinuteHourDayMonthChanged,
    isOnlyDayChanged,
    isOnlyMonthChanged,
    isOnlyWeekChanged,
    isOnlyYearChanged
  };
};

const fieldChangeStatus = computed(getFieldChangeStatus);

// 计算表达式表格数据
const expressionData = computed(() => {
  const data: Record<string, string> = {};
  CRON_FIELDS.forEach(field => {
    data[field.name] = getFieldValue(field.name);
  });
  return data;
});

// 在 getFieldValue 函数中修改 handleEveryCase 部分
const getFieldValue = (field: string): string => {
  const config = state[field as keyof CronState] as any;
  const {
    modifiedFields,
    isOnlyMinuteChanged,
    isOnlyHourChanged,
    isMinuteAndHourChanged,
    isMinuteHourDayChanged,
    isMinuteHourDayMonthChanged,
  } = fieldChangeStatus.value;

  const handleEveryCase = (): string => {
    // 根据字段层级关系设置默认值
    if (field === 'second') {
      // 如果任何更高级别的字段被修改，秒应该设为0
      if (modifiedFields.minute || modifiedFields.hour || modifiedFields.day ||
        modifiedFields.month || modifiedFields.week || modifiedFields.year) {
        return '0';
      }
    }

    if (field === 'minute') {
      // 如果小时、日、月、周、年被修改，分钟应该设为0
      if (modifiedFields.hour || modifiedFields.day || modifiedFields.month ||
        modifiedFields.week || modifiedFields.year) {
        return '0';
      }
    }

    if (field === 'hour') {
      // 如果日、月、周、年被修改，小时应该设为0
      if (modifiedFields.day || modifiedFields.month || modifiedFields.week || modifiedFields.year) {
        return '0';
      }
    }

    if (field === 'day') {
      // 如果月、周、年被修改，日应该设为合适的默认值
      if (modifiedFields.month || modifiedFields.week || modifiedFields.year) {
        return '1'; // 从第1天开始
      }
    }

    if (field === 'month') {
      // 如果周、年被修改，月应该设为合适的默认值
      if (modifiedFields.week || modifiedFields.year) {
        return '1'; // 从第1月开始
      }
    }

    return '*';
  };

  const handleIntervalCase = (): string => {
    // 对于分钟字段，如果是单独修改或者是组合修改的一部分，使用0作为起始点
    if (field === 'minute' && (isOnlyMinuteChanged || isMinuteAndHourChanged || isMinuteHourDayChanged || isMinuteHourDayMonthChanged)) {
      return `0/${formatNumber(config.intervalStep)}`;
    }

    // 对于小时字段，如果是单独修改或者是组合修改的一部分，使用0作为起始点
    if (field === 'hour' && (isOnlyHourChanged || isMinuteAndHourChanged || isMinuteHourDayChanged || isMinuteHourDayMonthChanged)) {
      return `0/${formatNumber(config.intervalStep)}`;
    }

    // 对于日字段，如果是组合修改的一部分，使用1作为起始点
    if (field === 'day' && (isMinuteHourDayChanged || isMinuteHourDayMonthChanged)) {
      return `1/${formatNumber(config.intervalStep)}`;
    }

    // 对于月字段，如果是组合修改的一部分，使用1作为起始点
    if (field === 'month' && isMinuteHourDayMonthChanged) {
      return `1/${formatNumber(config.intervalStep)}`;
    }

    // 默认情况
    return `${formatNumber(config.intervalFrom)}/${formatNumber(config.intervalStep)}`;
  };

  const handleSpecificCase = (): string => {
    if (config.specificSpecific.length === 0) return '*';
    return config.specificSpecific.map((v: string) => formatNumber(v)).join(',');
  };

  const handleUnspecifiedCase = (): string => {
    const unspecifiedFields = ['week', 'day', 'month'];
    if (unspecifiedFields.includes(field)) return '?';
    if (field === 'year') return '';
    return '*';
  };

  // 特殊处理周字段的"last"情况
  if (field === 'week' && config.cronEvery === 'last') {
    return `${formatNumber(config.lastDay)}L`;
  }

  switch (config.cronEvery) {
    case 'every':
      return field === 'year' ? '*' : handleEveryCase();
    case 'weekly':
      if (field === 'week') return '*';
      return ['second', 'minute', 'hour'].includes(field) ? '0' : '*';
    case 'cycle':
      return `${formatNumber(config.cycleFrom)}-${formatNumber(config.cycleTo)}`;
    case 'interval':
      return handleIntervalCase();
    case 'specific':
      return handleSpecificCase();
    case 'workday':
      return `${formatNumber(config.workday)}W`;
    case 'last':
      // 周字段的last已经在上面特殊处理了
      if (field === 'week') return `${formatNumber(config.lastDay)}L`;
      return 'L';
    case 'nth':
      return `${formatNumber(config.nthWeek)}#${formatNumber(config.nthDay)}`;
    case 'yearly':
      return '';
    case 'unspecified':
      return handleUnspecifiedCase();
    default:
      return '*';
  }
}
const generateCron = (): void => {
  try {
    const cronParts = CRON_FIELDS
      .map(field => getFieldValue(field.name))
      .filter(value => value !== '');

    state.generatedCron = cronParts.join(' ');
    state.errorMessage = '';

    // 验证日和周的冲突
    if (state.week.cronEvery !== 'yearly') {
      const dayIndex = CRON_FIELDS.findIndex(f => f.name === 'day');
      const weekIndex = CRON_FIELDS.findIndex(f => f.name === 'week');
      const dayValue = cronParts[dayIndex];
      const weekValue = cronParts[weekIndex];

      if (dayValue !== '?' && weekValue !== '?') {
        state.errorMessage = '日和周不能同时指定具体值，其中一个必须为?';
      }
    }
  } catch (error) {
    state.errorMessage = '生成表达式时出现错误';
    console.error('Cron generation error:', error);
  }
};

const parseCron = (): void => {
  try {
    const cron = state.generatedCron.trim();
    console.log('=== parseCron 开始 ===');
    console.log('原始cron:', cron);

    if (!cron) {
      state.errorMessage = 'Cron表达式不能为空';
      return;
    }

    const parts = cron.split(/\s+/);
    console.log('分割parts:', parts);
    console.log('parts长度:', parts.length);

    if (parts.length < 6 || parts.length > 7) {
      state.errorMessage = 'Cron表达式格式错误，应为6或7个字段';
      return;
    }

    // 解析字段
    const parsedParts = parseCronParts(parts);
    console.log('parseCronParts 结果:', parsedParts);

    // 检查是否为每年模式
    if (isYearlyMode(parsedParts)) {
      console.log('检测到每年模式');
      setYearlyMode();
      ElMessage.success('Cron表达式解析成功');
      return;
    }

    state.errorMessage = '';
    console.log('开始解析所有字段...');
    parseAllFields(parsedParts);
    console.log('解析完成，当前状态:', JSON.parse(JSON.stringify(state)));
    ElMessage.success('Cron表达式解析成功');
  } catch (error) {
    state.errorMessage = `解析Cron表达式时出现错误: ${error}`;
    ElMessage.error('解析Cron表达式失败');
    console.error('Cron parsing error:', error);
  }
};

// 完全重写 parseCronParts 函数，确保正确处理 0 0/1 0/1 1/1 1/1 ?
const parseCronParts = (parts: string[]) => {
  console.log('parseCronParts 输入:', parts);

  if (parts.length === 6) {
    // 检查是否是类似 "0 0/1 0/1 1/1 1/1 ?" 的格式
    // 这种格式的特点是：第一个字段是简单数字，后面字段有间隔表达式
    const firstField = parts[0];
    const secondField = parts[1];
    const thirdField = parts[2];

    const isFirstFieldSimple = /^\d+$/.test(firstField); // 纯数字
    const hasIntervalInSecond = secondField.includes('/'); // 第二个字段有间隔
    const hasIntervalInThird = thirdField.includes('/'); // 第三个字段有间隔

    console.log('6字段检测:', { isFirstFieldSimple, hasIntervalInSecond, hasIntervalInThird });

    if (isFirstFieldSimple && (hasIntervalInSecond || hasIntervalInThird)) {
      console.log('检测到 7字段格式（包含秒）');
      // 按7字段格式解析（秒 分 时 日 月 周）
      return {
        secondPart: parts[0],
        minutePart: parts[1],
        hourPart: parts[2],
        dayPart: parts[3],
        monthPart: parts[4],
        weekPart: parts[5],
        yearPart: undefined
      };
    }

    // 原有的特殊字符检测
    const weekIndex = parts.findIndex(part => part.includes('#'));
    const weekIndexL = parts.findIndex(part => part.includes('L'));
    const dayIndex = parts.findIndex(part => part.includes('W'));

    if (dayIndex === 3) {
      console.log('检测到 W 工作日格式');
      return { ...parts, secondPart: parts[0], minutePart: parts[1], hourPart: parts[2], dayPart: parts[3], monthPart: parts[4], weekPart: parts[5], yearPart: undefined };
    } else if (weekIndexL === 5) {
      console.log('检测到 L 最后一周格式');
      return { ...parts, secondPart: parts[0], minutePart: parts[1], hourPart: parts[2], dayPart: parts[3], monthPart: parts[4], weekPart: parts[5], yearPart: undefined };
    } else if (weekIndex === 5) {
      console.log('检测到 # 第N周格式');
      return { ...parts, secondPart: parts[0], minutePart: parts[1], hourPart: parts[2], dayPart: parts[3], monthPart: parts[4], weekPart: parts[5], yearPart: undefined };
    }

    console.log('按标准6字段格式解析');
    // 标准的6字段格式（分 时 日 月 周 年）
    return {
      secondPart: '0',
      minutePart: parts[0],
      hourPart: parts[1],
      dayPart: parts[2],
      monthPart: parts[3],
      weekPart: parts[4],
      yearPart: parts[5]
    };
  } else {
    console.log('7字段格式解析');
    // 7字段格式（秒 分 时 日 月 周 年）
    return {
      secondPart: parts[0],
      minutePart: parts[1],
      hourPart: parts[2],
      dayPart: parts[3],
      monthPart: parts[4],
      weekPart: parts[5],
      yearPart: parts[6]
    };
  }
};

const isYearlyMode = (parts: any): boolean => {
  return parts.secondPart === '0' && parts.minutePart === '0' && parts.hourPart === '0' &&
    parts.dayPart === '1' && parts.monthPart === '1' && parts.weekPart === '?' && parts.yearPart === '*';
};

const setYearlyMode = (): void => {
  state.week.cronEvery = 'yearly';
  state.second.cronEvery = 'every';
  state.minute.cronEvery = 'every';
  state.hour.cronEvery = 'every';
  state.day.cronEvery = 'every';
  state.month.cronEvery = 'every';
  state.year.cronEvery = 'every';
  state.errorMessage = '';
};

const parseAllFields = (parts: any): void => {
  parseField(parts.secondPart, 'second', 0, 59);
  parseField(parts.minutePart, 'minute', 0, 59);
  parseField(parts.hourPart, 'hour', 0, 23);
  parseDayField(parts.dayPart);
  parseField(parts.monthPart, 'month', 1, 12);
  parseWeekField(parts.weekPart);
  if (parts.yearPart) {
    parseYearField(parts.yearPart);
  }
};

// 通用字段解析函数
const parseField = (cronPart: string, field: string, min: number, max: number): void => {
  const config = state[field as keyof CronState] as any;
  resetFieldConfig(field);

  if (cronPart === '*') {
    config.cronEvery = 'every';
    return;
  }

  // 首先检查是否是间隔表达式: */5 或 0/5
  if (cronPart.includes('/')) {
    const [start, step] = cronPart.split('/');
    config.cronEvery = 'interval';

    // 处理起始值为 * 的情况
    if (start === '*') {
      config.intervalFrom = min;
    } else {
      config.intervalFrom = parseInt(start, 10);
      // 如果解析失败，使用最小值
      if (isNaN(config.intervalFrom)) {
        config.intervalFrom = min;
      }
    }

    config.intervalStep = parseInt(step, 10);
    // 如果步长解析失败，使用1
    if (isNaN(config.intervalStep)) {
      config.intervalStep = 1;
    }

    // 验证并修正数值范围
    config.intervalFrom = Math.max(min, Math.min(max, config.intervalFrom));
    config.intervalStep = Math.max(1, Math.min(max, config.intervalStep));
    return;
  }

  // 处理范围表达式: 1-5
  if (cronPart.includes('-')) {
    const [from, to] = cronPart.split('-');
    config.cronEvery = 'cycle';
    config.cycleFrom = parseInt(from, 10);
    config.cycleTo = parseInt(to, 10);

    // 验证并修正数值范围
    config.cycleFrom = Math.max(min, Math.min(max, config.cycleFrom));
    config.cycleTo = Math.max(min, Math.min(max, config.cycleTo));

    // 确保范围有效
    if (config.cycleFrom > config.cycleTo) {
      [config.cycleFrom, config.cycleTo] = [config.cycleTo, config.cycleFrom];
    }
    return;
  }

  // 处理逗号分隔的多个值: 1,3,5
  if (cronPart.includes(',')) {
    const values = cronPart.split(',')
      .map(v => {
        const num = parseInt(v, 10);
        return isNaN(num) ? v : padZero(num);
      })
      .filter(v => {
        const num = parseInt(v, 10);
        return !isNaN(num) && num >= min && num <= max;
      });

    if (values.length > 0) {
      config.cronEvery = 'specific';
      config.specificSpecific = values;
    } else {
      config.cronEvery = 'every';
    }
    return;
  }

  // 处理单个数字
  const numValue = parseInt(cronPart, 10);
  if (!isNaN(numValue) && numValue >= min && numValue <= max) {
    config.cronEvery = 'specific';
    config.specificSpecific = [padZero(numValue)];
    return;
  }

  // 默认情况
  config.cronEvery = 'every';
};


// 解析日期字段（特殊处理）
const parseDayField = (cronPart: string): void => {
  const config = state.day;
  resetFieldConfig('day');

  const specialCases: Record<string, () => void> = {
    '*': () => { config.cronEvery = 'every'; },
    '?': () => { config.cronEvery = 'unspecified'; },
    'L': () => { config.cronEvery = 'last'; }
  };

  if (specialCases[cronPart]) {
    specialCases[cronPart]();
    return;
  }

  // 处理工作日: 15W
  if (cronPart.endsWith('W')) {
    const dayStr = cronPart.replace('W', '');
    const day = parseInt(dayStr, 10);
    if (!isNaN(day) && day >= 1 && day <= 31) {
      config.cronEvery = 'workday';
      config.workday = day;
    } else {
      config.cronEvery = 'every';
    }
    return;
  }

  // 使用通用解析（包含间隔表达式处理）
  parseField(cronPart, 'day', 1, 31);
};


// 解析周字段（特殊处理）
const parseWeekField = (cronPart: string): void => {
  const config = state.week;
  resetFieldConfig('week');

  const specialCases: Record<string, () => void> = {
    '*': () => { config.cronEvery = 'weekly'; },
    '?': () => { config.cronEvery = 'unspecified'; }
  };

  if (specialCases[cronPart]) {
    specialCases[cronPart]();
    return;
  }

  // 处理最后一个星期X: 1L, 2L, 3L 等 (最后一个星期X)
  if (cronPart.endsWith('L')) {
    const dayStr = cronPart.replace('L', '');
    const day = parseInt(dayStr, 10);
    if (!isNaN(day) && day >= 1 && day <= 7) {
      config.cronEvery = 'last';
      config.lastDay = day;
    } else {
      config.cronEvery = 'unspecified';
    }
    return;
  }

  // 处理第N周的星期M: 2#3 (第3周的星期2)
  if (cronPart.includes('#')) {
    const [weekStr,dayStr] = cronPart.split('#');
    const day = parseInt(dayStr, 10);
    const week = parseInt(weekStr, 10);

    if (!isNaN(day) && day >= 1 && day <= 7 && !isNaN(week) && week >= 1 && week <= 5) {
      config.cronEvery = 'nth';
      config.nthDay = day;
      config.nthWeek = week;
    } else {
      config.cronEvery = 'unspecified';
    }
    return;
  }

  // 使用通用解析（包含间隔表达式处理）
  parseField(cronPart, 'week', 1, 7);
};

// 解析年字段
const parseYearField = (cronPart: string): void => {
  const config = state.year;
  resetFieldConfig('year');

  if (cronPart === '*' || cronPart === '') {
    config.cronEvery = 'every';
    return;
  }

  // 使用通用解析（包含间隔表达式处理）
  parseField(cronPart, 'year', 1970, 2099);
};

// 重置字段配置到默认值
const resetFieldConfig = (field: string): void => {
  const defaults: Record<string, any> = {
    second: createDefaultFieldConfig(),
    minute: createDefaultFieldConfig(),
    hour: createDefaultFieldConfig(),
    day: createDefaultDayConfig(),
    month: createDefaultFieldConfig(),
    week: createDefaultWeekConfig(),
    year: createDefaultYearConfig()
  };

  Object.assign(state[field as keyof CronState], defaults[field]);
};
const copyCron = async (): Promise<void> => {
  try {
    await navigator.clipboard.writeText(state.generatedCron);
    ElMessage.success('Cron表达式已复制到剪贴板');
  } catch (error) {
    // 降级方案
    const textArea = document.createElement('textarea');
    textArea.value = state.generatedCron;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand('copy');
    document.body.removeChild(textArea);
    ElMessage.success('Cron表达式已复制到剪贴板');
  }
};

defineExpose({
  getValue,
  setValue,
  copyCron
});

// 监听状态变化，自动生成表达式
watch(
  () => [
    state.second, state.minute, state.hour, state.day,
    state.month, state.week, state.year
  ],
  () => {
    generateCron();
  },
  { deep: true }
);

// 初始化生成表达式
generateCron();
</script>
  
<style lang="scss" scoped>
.vue3-cron-plus-container {
  max-width: 1200px;
  margin: 0 auto;

  .el-row {
    margin-bottom: 10px;
  }

  .tabBody {
    padding: 10px;
  }

  .long {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .myScroller {
    max-height: 400px;
    overflow-y: auto;
  }

  .expression-section {
    margin-top: 20px;
    padding: 20px;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
  }

  .expression-header {
    margin-bottom: 15px;

    h3 {
      margin: 0;
      color: #303133;
    }
  }

  .expression-table {
    margin-bottom: 20px;
  }

  .field-value {
    font-family: 'Courier New', monospace;
    font-weight: bold;
  }

  .cron-result {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 5px;
  }

  .cron-expression-display {
    margin-bottom: 10px;
    display: flex;
    align-items: center;
    gap: 10px;
  }

  .cron-string {
    font-family: 'Courier New', monospace;
    font-size: 14px;
    padding: 4px 8px;
  }

  .error-message {
    margin-bottom: 10px;
  }

  .action-buttons {
    display: flex;
    gap: 10px;
  }
}
</style>